package com.tupu.service.impl.permission;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tupu.entity.permission.OrganizationInfo;
import com.tupu.mapper.permission.OrganizationMapper;
import com.tupu.service.permission.OrganizationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, OrganizationInfo> implements OrganizationService {

    @Autowired(required = false)
    private OrganizationMapper organizationMapper;

    @Override
    public Page<OrganizationInfo> pageInfo(Integer page, Integer size, String name) {
        Page<OrganizationInfo> pageInfo = new Page<>(page, size);
        QueryWrapper<OrganizationInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.like("name", name);
        }
        queryWrapper.orderByAsc("organ_id");
        organizationMapper.selectPage(pageInfo, queryWrapper);
        return pageInfo;
    }

    @Override
    public List<OrganizationInfo> getAll() {
        List<OrganizationInfo> organizationInfo = organizationMapper.selectList(null);
        return organizationInfo;
    }

    @Override
    public OrganizationInfo selectById(Integer organId) {
        OrganizationInfo organization = organizationMapper.selectById(organId);
        return organization;
    }

    @Override
    public void add(OrganizationInfo organization) {
        if (StringUtils.isNotEmpty(organization.getName())) {
            Integer num = organizationMapper.findCountByName(organization.getName());
            if (0 != num) {
                return;
            }
            OrganizationInfo newOrganization = new OrganizationInfo();
            newOrganization.setName(organization.getName());
            newOrganization.setStatus(organization.getStatus());
            organizationMapper.insert(newOrganization);
        }
    }

    @Override
    public void delByIds(List<Integer> ids) {
        for (Integer id : ids) {
            organizationMapper.deleteById(id);
        }
    }

    @Override
    public Integer updateOrgan(OrganizationInfo organization) {
        Integer organId = organization.getOrganId();
        OrganizationInfo oldOrganization = organizationMapper.selectById(organId);
        if (oldOrganization.getName().equals(organization.getName())) {
            organizationMapper.updateById(organization);
            return 1;
        }
        Integer num = organizationMapper.findCountByName(organization.getName());
        if (0 == num) {
            organizationMapper.updateById(organization);
            return 1;
        } else {
            return 0;
        }
    }

}
